const R = require('@/models/Response')
const { ERROR_USER_CODE } = require('@/constants/errorCode')
const User = require('@/models/userModel')

/**
 * @description token验证的中间件
 * @param {boolean} required 是否需要token才能调通此接口
 * @param {boolean} isReflesh 是否验证刷新token
 * @returns
 */
module.exports.verifyAdmin = function (admin = true) {
  return async (ctx, next) => {
    const { id } = ctx.user
    const user = await User.findByPk(BigInt(id))
    if (admin) {
      if (+user.roleId === 1) {
        await next()
      } else {
        ctx.body = R.error(ERROR_USER_CODE.PERMISSION_ERROR)
        return
      }
    } else {
      await next()
    }
  }
}
